
import { PdfNodeProps, PdfTemplate } from '../types';
import * as PDF_TYPES from '../pdf'
import { Document, Page, View } from '@react-pdf/renderer';
import { JSX } from 'react';

// const NODE_TYPES: any = { ...PDF_TYPES }
const NODE_TYPES: any = PDF_TYPES;

export interface PdfDocumentProps {
    key?: string;
    nodes: PdfNodeProps[]
    unit?: string
}
// PDF 渲染组件
export const PdfDocument = ({ nodes, unit = '' }: PdfDocumentProps) => {
    const id = new Date().getTime();
    return (
      <Document key={id}>
        <Page size="A4" style={{ padding: 30 }}>
          <View
            style={{
              fontFamily: 'NotoSansCJK', // 使用注册的中文字体
              fontSize: 12,
            }}
          >
            {nodes.map((node) => {
              const NodeComponent = NODE_TYPES[node.type!] as (
                props: any,
              ) => JSX.Element;
              const style = {
                position: 'absolute',
                left: node.position!.x + unit,
                top: node.position!.y + unit,
                width: node.width + unit,
                height: node.height + unit,
                ...node.data?.style,
              };
              return (
                <NodeComponent key={node.id} {...node.data} style={style} />
              );
            })}
          </View>
        </Page>
      </Document>
    );
}
PdfDocument.loadData = async (template: PdfTemplate) => {
    for (const key in NODE_TYPES) {
        const NodeType = NODE_TYPES[key];
        await NodeType.loadData?.(template.nodes);
    }
    return template;
}